package client.ui;

import client.business.ContactManager;
import server.db.Contact;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class EditContactDialog extends JDialog {
    private JTextField nameField;
    private JTextField phoneField;
    private JTextField addressField;
    private JButton saveButton;
    private JButton cancelButton;
    private ContactManager contactManager;
    private String originalName;

    public EditContactDialog(Frame owner, String contactName) {
        super(owner, "修改联系人", true);
        contactManager = new ContactManager();
        originalName = contactName;

        Contact contact = getContactByName(contactName);
        if (contact == null) {
            JOptionPane.showMessageDialog(this, "未能找到联系人");
            dispose();
            return;
        }

        nameField = new JTextField(contact.getName(), 20);
        phoneField = new JTextField(contact.getPhone(), 20);
        addressField = new JTextField(contact.getAddress(), 20);
        saveButton = new JButton("保存");
        cancelButton = new JButton("取消");

        setLayout(new GridLayout(4, 2));
        add(new JLabel("姓名:"));
        add(nameField);
        add(new JLabel("电话号码:"));
        add(phoneField);
        add(new JLabel("地址:"));
        add(addressField);
        add(saveButton);
        add(cancelButton);

        saveButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String name = nameField.getText();
                String phone = phoneField.getText();
                String address = addressField.getText();
                contactManager.editContact(originalName, phone, address);
                dispose();
            }
        });

        cancelButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });

        pack();
        setLocationRelativeTo(owner);
    }

    private Contact getContactByName(String name) {
        for (Contact contact : contactManager.getAllContacts()) {
            if (contact.getName().equals(name)) {
                return contact;
            }
        }
        return null;
    }
}
